package service

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"math/rand"
	"time"
	"zhuandan/redis_lib"
	"zhuandan/tool"
)

type MemberService struct {
}

func (ms *MemberService) Sendcode(phone string) bool {
	//1产生一个验证码
	code := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(100000))
	//验证码加入redis
	ctx := context.Background()
	redis_lib.Client.Set(ctx, phone, code, 600*time.Second)

	//2调用阿里云sdk
	config := tool.GetConfig().Sms
	client, err := dysmsapi.NewClientWithAccessKey(config.RegionId, config.AppKey, config.AppSecret)
	if err != nil {
		return false
	}
	request := dysmsapi.CreateSendSmsRequest()
	request.Scheme = "https"
	request.PhoneNumbers = phone
	request.SignName = config.SignName
	request.TemplateCode = config.TemplateCode
	par, err := json.Marshal(map[string]interface{}{
		"code": code,
	})
	request.TemplateParam = string(par)
	response, err1 := client.SendSms(request)
	//fmt.Println(response)
	if err1 != nil {
		return false
	}

	//3结束阿里云结果 并且发送给调用
	if response.Code == "OK" {
		return true
	}
	return false
}
